import random
import hashlib
import threading
import layering
import time
import tttds
import tttd
from concurrent .futures  import ThreadPoolExecutor
import os
import bsw
from bsw import cal_hash
from layering  import hash_file_dir, hash_value_exist, record_hash

a=0
start_time=time.time()
file_path = input("请输入所要分块的文件路径")
way = input("请输入分块方法").strip().lower()
if way == 'tttds':
    tttds = tttds.Tttds()
    break_points = tttds.Tttds_break(file_path)
elif way == 'bsw':
    break_points = bsw.bsw(file_path)
elif way == 'tttd':
    tttd = tttd.Tttd()
    break_points = tttd.Tttd_break(file_path)

else:
    a=1



# def cal_hash(file_content):
#     # 确保输入是字节类型
#     if not isinstance(file_content, bytes):
#         raise TypeError("输入必须是字节类型")
#     # 创建 SHA-256 对象
#     sha256_hash = hashlib.sha256()
#     # 用数据更新哈希对象
#     sha256_hash.update(file_content)
#     # 计算并返回哈希值

def write_chunk(args):

    i, chunk_data = args
    hash_value = cal_hash(chunk_data)
    if not layering .hash_value_exist(hash_value):
        layering .record_hash(chunk_data, hash_value)
def chunking(break_points,file_path,max_works):
    task=[]
    las=0
    with open(file_path ,'rb')as f:
        for i,now in enumerate (break_points ):
            if now<=las:
                continue
            data=f.read(now-las)
            if data:

                task.append(( i,data))
            las=now
        if las<os.path .getsize(file_path ):
            f.seek(las)
            data=f.read()
            if data:

                task.append((i,data))
    with ThreadPoolExecutor (max_works )as executor:
        executor.map(write_chunk,task)

def main():
    file_list =file_path .split('\\')
    file_name=file_list[len(file_list )-1]
    global break_points
    if a:
        return
    chunking(break_points, file_path,max_works= 4)


    with open(file_path ,'rb') as of:
        data=of.read()
        file_hash_path=f'{file_name}_hash'
        with open(file_hash_path, 'a') as f:
            las = 0
            for i in break_points:
                if i > las:
                    hash_value=cal_hash(data[las:i])
                    hash_value = format(hash_value, 'x')
                    f.writelines(f'{str(hash_value )}'+'\n' )
                    las=i

    end_time = time.time()

    #print(f"程序运行了{end_time-start_time }秒")
if __name__=="__main__":
    main()